<!DOCTYPE html>
<html class="x-admin-sm">
    <head>
        <meta charset="UTF-8">
        <title>欢迎页面-X-admin2.2</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
        <link rel="stylesheet" href="./css/font.css">
        <link rel="stylesheet" href="./css/xadmin.css">
		<link rel="stylesheet" href="css/tooltip.css" />
		<link rel="stylesheet" href="js/Cesium/Widgets/widgets.css" />
        <script src="./lib/layui/layui.js" charset="utf-8"></script>
        <script type="text/javascript" src="./js/xadmin.js"></script>
		<script src="js/Cesium/Cesium.js"></script>
		<script src="js/Cesiumtool/viewerCesiumNavigationMixin.js"></script>
		<script src="js/Cesiumtool/GlobeTooltip.js"></script>
        <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
        <!--[if lt IE 9]>
          <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
          <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
		<style>
			html,body{
				margin: 0;
				padding: 0;
				height: 100%;
				width: 100%;
			}
			#contanter{
				width:100%;
				height:100%
			}    
			/* 去除logo信息 */	
			.cesium-widget-credits{ 
				display:none!important; 
				visibility:hide!important; 
			} 
			/* 导航条的位置 */
			.compass{
				left:0px;
				top:20px
			}
			.navigation-controls{
				left:30px;
				top:110px
			}
			
			/* 添加点、线、面的按钮*/
			.addEntities{
				position: fixed;
				left: 110px;
				top: 10px;
				z-index: 99999;
			}
			.addEntities button{
				background-color: rgba(47,53,60,0.8);
				color: #FFFFFF;
				border: 0;
				padding: 5px 15px;
				border-radius: 5px;
			}
		</style>
    </head>
    <body>
		<div id="contanter"></div>
		<!-- 添加实体 -->
		<div class="addEntities">
			<button onclick="measurLength()">长度量测</button>
			<button onclick="measurarea()">面积量测</button>
			<button onclick="measurthree()">高度量测</button>
			<button onclick="clearEntities()">清除</button>
		</div>
		<script>
			var viewer = new Cesium.Viewer("contanter",{
				animation: false,  //是否显示动画控件
	            baseLayerPicker: false, //是否显示图层选择控件
	            geocoder: true, //是否显示地名查找控件
	            timeline: false, //是否显示时间线控件
	            sceneModePicker: true, //是否显示投影方式控件
	            navigationHelpButton: false, //是否显示帮助信息控件
	            infoBox: true,  //是否显示点击要素之后显示的信息
				// 加载地形数据
				terrainProvider: new Cesium.CesiumTerrainProvider({
					url: Cesium.IonResource.fromAssetId(3956)
				})
			})
			
			// 显示导航条	        
			viewer.extend(Cesium.viewerCesiumNavigationMixin, {});
			//取消双击事件   
			viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
			
			var tooltip = new GlobeTooltip(viewer.container);	
			var scene = viewer.scene;
			
			// 绘制线
			function measurLength(){
				// 点集合
				var positions = []
				// 创建鼠标事件
				var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
				// 鼠标移动事件
				handler.setInputAction(function(movement) {
					tooltip.showAt(movement.endPosition, "<p>点击绘制</p>")
					 // var newPosition1 = viewer.scene.pickPosition(movement.endPosition);
					 // console.log(newPosition1)
					 var newPosition = getPosition(movement.endPosition);	
					if(newPosition&&positions.length>0){
						
						positions.pop();
						positions.push(newPosition);
					}
					if(positions.length>=2){
						var dis = getSpaceDistance(positions);
						var text = dis>1000?(dis/1000).toFixed(2)+"KM":dis+"m";
						tooltip.showAt(movement.endPosition, "<p>总长度:"+text+"右键结束绘制</p>")
					}
				},Cesium.ScreenSpaceEventType.MOUSE_MOVE);
				// 左键
				handler.setInputAction(function(movement) {
					var position = getPosition(movement.position)
					if(position){
						if(positions.length==0){
							positions.push(position)
							showPolyLine(positions)
						}
						positions.push(position)
						var text = "起点"
						if(positions.length>=2){
							console.log("距离",getSpaceDistance(positions))
							var dis = getSpaceDistance(positions);
							text = dis>1000?(dis/1000).toFixed(2)+"KM":dis+"m";
						}
						creatPoint(position,text)
					}	
					tooltip.showAt(movement.position, "<p>移动继续点击绘制</p>")
				},Cesium.ScreenSpaceEventType.LEFT_CLICK);
				// 右键
				handler.setInputAction(function(movement) {
					positions.pop()
					handler.destroy();
					tooltip.setVisible(false)
				},Cesium.ScreenSpaceEventType.RIGHT_CLICK);
			}
			// 绘制多边形
			function measurarea(){
				// 点集合
				var positions = []
				var tempPoints = [];
				// 创建鼠标事件
				var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
				// 鼠标移动事件
				handler.setInputAction(function(movement) {
					tooltip.showAt(movement.endPosition, "<p>点击绘制</p>")
					 // var newPosition1 = viewer.scene.pickPosition(movement.endPosition);
					 // console.log(newPosition1)
					 var newPosition = getPosition(movement.endPosition);	
					if(newPosition&&positions.length>0){
						tooltip.showAt(movement.endPosition, "<p>移动绘制下一点，右键结束绘制</p>")
						positions.pop();
						positions.push(newPosition);
					}
				},Cesium.ScreenSpaceEventType.MOUSE_MOVE);
				// 左键
				handler.setInputAction(function(movement) {
					// console.log("左键",viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid))
					var position = getPosition(movement.position)
				
					if(position){
						if(positions.length==0){
							// creatPoint(position)
							positions.push(position)
							showPolygon(positions)
						}
						positions.push(position)
						//在三维场景中添加点
						var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
						var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
						var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
						var heightString = cartographic.height;
						tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});
						// 添加点
						creatPoint(position)
					}	
					tooltip.showAt(movement.position, "<p>移动继续点击绘制</p>")
				},Cesium.ScreenSpaceEventType.LEFT_CLICK);
				// 右键
				handler.setInputAction(function(movement) {
					positions.pop()
					handler.destroy();
					tooltip.setVisible(false)
					var textArea = getArea(tempPoints,positions) + "平方公里";
					creatPoint(positions[positions.length-1],textArea)

				},Cesium.ScreenSpaceEventType.RIGHT_CLICK);
			}
			// 绘制三角
			function measurthree(){
				// 点集合
				var positions = []
				var tempPoints =null
				// 创建鼠标事件
				var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
				// 鼠标移动事件
				handler.setInputAction(function(movement) {
					tooltip.showAt(movement.endPosition, "<p>点击绘制</p>")
					 var newPosition = getPosition(movement.endPosition);	
					if(newPosition&&positions.length>0){
						positions.pop();
						positions.push(newPosition);
					}
				},Cesium.ScreenSpaceEventType.MOUSE_MOVE);
				// 左键
				handler.setInputAction(function(movement) {
					var position = getPosition(movement.position)
					if(position){
						if(positions.length==0){
							positions.push(position)
							showPolyLine(positions)
							tooltip.showAt(movement.position, "<p>移动继续点击绘制</p>")
						}
											
						positions.push(position)
						creatPoint(position,"")
						if(positions.length>2){
							handler.destroy()
							positions.pop()
							tooltip.setVisible(false)
							tempPoints= point_conf(positions);
							var height = getHeight([positions[0],tempPoints])+"米"
							var distance = getDistance([positions[1],tempPoints])+"米"
							var dis = getSpaceDistance(positions);
							var text = dis>1000?(dis/1000).toFixed(2)+"KM":dis+"m";
							var bData1 = {
							    polyline: {
							        positions: [positions[0],tempPoints],
							        width: 2,
							        material:Cesium.Color.AQUA
							    }
							};
							viewer.entities.add(bData1);
							var bData = {
							    polyline: {
							        positions: [positions[1],tempPoints],
							        // clampToGround: true,
							        width: 2,
							        material:Cesium.Color.AQUA
							    }
							};
							viewer.entities.add(bData);
							creatPoint(positions[0],height)
							creatPoint(positions[1],text)
							creatPoint(tempPoints,distance)
						}
					}	
					
				},Cesium.ScreenSpaceEventType.LEFT_CLICK);
				// 右键
				handler.setInputAction(function(movement) {
					positions.pop()
					handler.destroy();
					tooltip.setVisible(false)
				},Cesium.ScreenSpaceEventType.RIGHT_CLICK);
			}
			// 清除所有
			function clearEntities(){
				
				viewer.entities.removeAll()
			}
			// 获取鼠标点击的坐标信息
			function getPosition(position){
				// var wp = event.position;
				if (!Cesium.defined(position)) {
				    return;
				}
				var ray = viewer.camera.getPickRay(position);
				if (!Cesium.defined(ray)) {
				    return;
				}
				var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
				if (!Cesium.defined(cartesian)) {
				    return;
				}
				return cartesian
			}
			
			// 绘制点
			function creatPoint(position,textDisance){
				viewer.entities.add({
					name: "点几何对象",
					position: position,
					point: {
                        pixelSize: 5,
                        color: Cesium.Color.RED,
                        outlineColor: Cesium.Color.WHITE,
                        outlineWidth: 2,
                        heightReference:Cesium.HeightReference.NONE
                    },
                    label: {
                        text: textDisance?textDisance:'',
                        font: '16px sans-serif',
                        fillColor: Cesium.Color.GOLD,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        outlineWidth: 2,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        pixelOffset: new Cesium.Cartesian2(0, -10),
                        heightReference:Cesium.HeightReference.NONE
                    }
				});
			}
			// 动态绘制线
			function showPolyLine(positions){
				var dynamicPositions = new Cesium.CallbackProperty(function () {
				    return positions;
				}, false);
				
				var bData = {
				    polyline: {
				        positions: dynamicPositions,
				        clampToGround: true,
				        width: 2,
				        material:Cesium.Color.AQUA
				    }
				};
				viewer.entities.add(bData);
			}
			// 动态绘制多边型
			function showPolygon(positions){
				var dynamicPositions = new Cesium.CallbackProperty(function () {
					if (positions.length > 2) {
						var pHierarchy = new Cesium.PolygonHierarchy(positions);
						return pHierarchy;
					} else {
						return null;
					}
				}, false);
				if(dynamicPositions)
				viewer.entities.add({
					polygon: {
						hierarchy: dynamicPositions,
						material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
					}
				});
			}
			
			 //空间两点距离计算函数
			function getSpaceDistance(positions) {
				var distance = 0;
				for (var i = 0; i < positions.length - 1; i++) { 
					var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
					var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i+1]);
					/**根据经纬度计算出距离**/
					var geodesic = new Cesium.EllipsoidGeodesic();
					geodesic.setEndPoints(point1cartographic, point2cartographic);
					var s = geodesic.surfaceDistance;
					//返回两点之间的距离
					s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));	
					distance = distance + s;
				}	
				return distance.toFixed(2);    
			}
			
			//----------------------计算多边形面积-----------------------------------------
			var radiansPerDegree = Math.PI / 180.0;//角度转化为弧度(rad) 
			var degreesPerRadian = 180.0 / Math.PI;//弧度转化为角度

			function getArea(points,positions) {
				var res = 0;
				//拆分三角曲面
				for (var i = 0; i < points.length - 2; i++) {
					var j = (i + 1) % points.length;
					var k = (i + 2) % points.length;
					var totalAngle = Angle(points[i], points[j], points[k]);
					var dis_temp1 = distance(positions[j], positions[0]);
					var dis_temp2 = distance(positions[k], positions[0]);
					res += dis_temp1 * dis_temp2 * Math.sin(totalAngle) / 2;
				}
				return Math.abs((res / 1000000.0).toFixed(4));
			}
			// 角度
			function Angle(p1, p2, p3) {
				var bearing21 = Bearing(p2, p1);
				var bearing23 = Bearing(p2, p3);
				var angle = bearing21 - bearing23;
				if (angle < 0) {
					angle += 360;
				}
				return angle;
			}
			/*方向*/
			function Bearing(from, to) {
				var lat1 = from.lat * radiansPerDegree;
				var lon1 = from.lon * radiansPerDegree;
				var lat2 = to.lat * radiansPerDegree;
				var lon2 = to.lon * radiansPerDegree;
				var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
				if (angle < 0) {
					angle += Math.PI * 2.0;
				}
				angle = angle * degreesPerRadian;//角度
				return angle;
			} 
			function distance(point1,point2){
				var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
				var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
				/**根据经纬度计算出距离**/
				var geodesic = new Cesium.EllipsoidGeodesic();
				geodesic.setEndPoints(point1cartographic, point2cartographic);
				var s = geodesic.surfaceDistance;
				//console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
				//返回两点之间的距离
				s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));	
				return s;
			}
			// ---------------------------计算多边形面积---------------------------------------
			
			// -----------------------------绘制三角----------------------------------------------------
			   // 获取直角点
				function point_conf(_positions){
			        var cartographic = Cesium.Cartographic.fromCartesian(_positions[0]);
			        var cartographic1 = Cesium.Cartographic.fromCartesian(_positions[1]);			
			        var point_temp= Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude),cartographic1.height);
			        return 	point_temp;			
			    }
				// 高度量测
				function getHeight(positions){
					var cartographic = Cesium.Cartographic.fromCartesian(positions[0]);
					var cartographic1 = Cesium.Cartographic.fromCartesian(positions[1]);
					var height_temp = cartographic1.height - cartographic.height;				
					return height_temp.toFixed(2);    			
				}
				// 水平量测
				function getDistance(positions){
					var point1cartographic = Cesium.Cartographic.fromCartesian(positions[1]);
					var point2cartographic = Cesium.Cartographic.fromCartesian(positions[0]);
					/**根据经纬度计算出距离**/
					var geodesic = new Cesium.EllipsoidGeodesic();
					geodesic.setEndPoints(point1cartographic, point2cartographic);
					var s = geodesic.surfaceDistance;
					//console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
					//返回两点之间的距离
					s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));	
					return s;
				}
	
			
			// -----------------------------绘制三角----------------------------------------------------
	
		</script>
    </body>
</html>